package com.hotelvip.common.exception;

import com.hotelvip.common.utils.JSONResult;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常全局处理
 * @author Lzh
 * @date 2020/11/30 15:31
 */
@RestControllerAdvice  //@ControllerAdvice+@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 处理shiro框架异常
     * @param e
     * @return
     */
    @ExceptionHandler(ShiroException.class)
    //@ResponseBody
    public JSONResult doHandleShiroException(
            ShiroException e, ServletResponse response) {
        JSONResult r=new JSONResult();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(401);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        r.setStatus(401);
        if(e instanceof UnknownAccountException) {
            r.setMsg("账户不存在");
        }else if(e instanceof LockedAccountException) {
            r.setMsg("账户已被禁用");
        }else if(e instanceof IncorrectCredentialsException) {
            r.setMsg("密码不正确");
        }else if(e instanceof AuthorizationException) {
            r.setMsg("没有此操作权限");
        }else {
            r.setMsg("系统维护中");
        }
        e.printStackTrace();
        return r;
    }

    /**
     * 	  @ExceptionHandler 注解描述的方法为一个异常处理方法,注解中定义的
     * 	异常类型,为当前方法的可以处理的异常处理类型(当然也可以处理异常类型的子类类
     * 	型).在异常处理方法中通常会定义一个异常参数,来接收异常对象.
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    //@ResponseBody
    public JSONResult doHandleRuntimeException(RuntimeException e) {
//        System.out.println("GlobalExceptionHandler.doHandleRuntimeException");
        e.printStackTrace();//在控制台输出异常信息
        return JSONResult.errorException(e);
    }
}
